<?php
/*----------------------------------------------------------------------
 * 同步客户端用户操作日志
 * Author: zhanagshiping
----------------------------------------------------------------------*/

namespace Common\Logic;

class ApiLogLogic{

    protected $status=array(
        0 => array('msgCode'=>1,'message'=>'success'),
        1 => array('msgCode'=>0,'message'=>'false')
    );

    //同步各种数据表
    public function syncTab($params){
        $params = $this->filterParam($params);//参数过滤
        if($params['tab']=='OrgPlay'){ //播放日志数据直接暂存redis
            $res = D('Common/Cache','Logic')->RPUSH(C('DATA_KEY.SYNC_TAB').':'.$params['tab'].':'.$params['host_name'],json_encode($params));
            return $this->status[$res===false];
        }elseif($params['tab']=='OrgHall'){
            $res = D('Common/Cache','Logic')->RPUSH(C('DATA_KEY.SYNC_TAB').':OrgHall',json_encode($params));
            return $this->status[$res===false];
        }elseif($params['tab']=='SHUNWANG'){
            $res = D('Common/Cache','Logic')->HSET(C('DATA_KEY.SYNC_DATACENTER').':'.$params['tab'].':'.$params['key'],$params['mac'].':'.$params['vid'].':'.$params['ctime'],json_encode($params));
            return $this->status[$res===false];
        }


        //查询院线主机信息
        $option['where']['host_name'] = array('eq',$params['host_name']);
        $option['limit'] = 1;
        $option['field'] = 'id,`type`,`host_ip`';
        $cimema = D('CinemaHost')->select($option);
        $cimema_id = $cimema[0]['id'];
        $cimema_type = $cimema[0]['type'];
        $cimema_ip = trim($cimema['host_ip']);

        if(!$cimema_id)return $this->status[1]; //没有主机信息
        //if($cimema_ip && $cimema_ip!=get_client_ip())return $this->status[1]; //客户端的host_name配置错误
        //查询上次更新记录
        $option1['where']['cinema_id']= array('eq',$cimema_id);
        $option1['order'] = 'id DESC';
        $option1['field'] = 'id,sub_id';
        $model = D($params['tab']);
        $old = $model->find($option1);//查询上次最新同步数据,区分修改数据跟新增数据

        //增加或更新记录
        $flog = true;
        $data = array();

        $model->startTrans();
        foreach ($params['list'] as $row) {
            $row['cinema_id'] = $cimema_id;
            if($params['tab']=='OrgPlay')$row['cinema_type'] = $cimema_type;
            $row['sub_id'] = $row['id'];
            unset($row['id']);
            if ($row['sub_id'] <= $old['sub_id']) { //修改记录
                $map['sub_id'] = $row['sub_id'];
                $map['cinema_id'] = $cimema_id;
                if ($model->where($map)->save($row) === false){

                    //如果该条数据存在又修改失败了,就算失败了.没有旧数据的情况不管,防止院线重复提交数据
                   if($model->where($map)->find())$flog = false;
                }
            } else {
                $data[] = $row;
            }
        }
        if($data){
            $model->addAll($data,[],true)===false AND $flog = false;
        }
        if(!$flog){
            $model->rollback();
            return $this->status[1];
        }
        //全部成功提交事务返回状态
        return $this->status[!$model->commit()];

    }

    //插入日志
    public function insertLogs($params) {
        foreach($params['data'] as &$row){
            $row['sub_id'] = $row['id'];
            unset($row['id']);
            $row['host_name'] = $params['host_name'];
        }
        return $this->status[!D('ApiLog')->addAll($params['data'])];
    }

    //每天定时更新影院影厅最近一个月的使用次数
    public function syncHallUseNum($params){
        $params = $this->filterParam($params);//参数过滤
        $count = count($params);
        $num = 0;
        foreach($params as $row){
            $sql = "UPDATE ".C('DB_PREFIX')."cinema_hall SET use_num=".$row['count']." WHERE host_name='".$row['host_name']."' AND hall_id=".$row['hall_id'].";";
            $res = D()->execute($sql);
            if($res!==false)++$num;
        }
        if($count==$num){
            $cinemaLogic = new \Common\Logic\CinemaLogic();
            $cinemaLogic->updataCache();
            return $this->status[0];
        }
        return $this->status[1];
    }

    //同步包时影厅折扣价
    public function syncHallDiscount($params){
        $params = $this->filterParam($params);//参数过滤
        $cnt = 0;
        if(!$params['data_list'] || !$params['host_name']) $this->status[1];
        $min_price = array();
        foreach($params['data_list'] as $hall_id=>$row){
            if(intval($hall_id)>0){
                $min_price[0]===null AND $min_price[0] = $row['price_dis']; //默认值
                $min_price[1]===null AND $min_price[1] = $row['price2_dis2']; //默认值
                $min_price[0] = $min_price[0]>$row['price_dis'] ? $row['price_dis'] : $min_price[0]; //最低包片价格
                $min_price[1] = $min_price[1]>$row['price2_dis2'] ? $row['price2_dis2'] : $min_price[1]; //最低包时价格
                $old_price = D('Common/Cache','Logic')->HGET(C('HALL_DIS_PRICE').':'.$params['host_name'],$hall_id);
                if($old_price==$row['price2_dis2'].','.$row['price_dis']){
                    continue;
                }
                $sql = "UPDATE ".C('DB_PREFIX')."cinema_hall SET price2_dis2=".$row['price2_dis2'].",price_dis=".$row['price_dis']." WHERE host_name='".$params['host_name']."' AND hall_id=".$hall_id.";";
                $res = D()->execute($sql);
                //缓存折扣价格
                $res!==false AND D('Common/Cache','Logic')->HSET(C('HALL_DIS_PRICE').':'.$params['host_name'],$hall_id,$row['price2_dis2'].','.$row['price_dis']);
                $cnt += intval($res);
            }
        }
        if($cnt>0){//折扣有修改，更新web缓存
            //更新排序统计
            $options['where']['is_online'] = array('eq',1);
            $options['where']['is_web'] = array('eq',1);
            $options['where']['type'] = array('eq',1);
            $options['where']['host_name'] = array('eq',$params['host_name']);
            $options['field'] = 'id,host_name,min_price,cinema_play_module';
            $cinema =  D('Common/CinemaHost')->getOne($options); //影院详情
            if(!$cinema){
                return $this->status[0];
            }
            //混合模式
            if(strpos($cinema['cinema_play_module'],'2')!==false && strpos($cinema['cinema_play_module'],'1')!==false){
                $min_price_res = $min_price[0]>$min_price[1]*2 ? $min_price[1]*2 : $min_price[0]; //最低价格
            //包时模式
            }elseif(strpos($cinema['cinema_play_module'],'2')!==false){
                $min_price_res = $min_price[1]*2; //最低价格
            //包片模式
            }else{
                $min_price_res = $min_price[0]; //最低价格
            }
            //最低价格有变化修改最低价
            if($cinema['min_price']!=$min_price_res){
                $where['id'] = array('eq',$cinema['id']);
                D('Common/CinemaHost')->where($where)->save(array('min_price'=>$min_price_res));
            }
            $cinemaLogic = new \Common\Logic\CinemaLogic();
            $cinemaLogic->updataCache();
        }
        return $this->status[0];
    }

    public function filterParam($data){
        $filters    =   isset($filter)?$filter:C('DEFAULT_FILTER');
        if($filters) {
            if(is_string($filters)){
                $filters    =   explode(',',$filters);
            }
            foreach($filters as $filter){
                $data   =   array_map_recursive($filter,$data); // 参数过滤
            }
        }
        is_array($data) && array_walk_recursive($data,'think_filter');
        return $data;
    }
}
